import requests
import time
import hmac
import hashlib

api_key = 'oMlYVBgANplqH7XilK0rzJ47r7p1R3MWoywVNBYOGvj5UHYXebQnxZjX9kLpdd5V'
secret_key = '8587vRjV45QsPPXhlrn3vcBdUwQJFA6HIBqfaVbJO7UqhhqTcVrQCR4GEO6w4OtN'

symbol = 'BTCUSDT'  # 交易对

# 1. 构建请求参数
params = {
    'symbol': symbol,
    # 'timestamp': int(time.time() * 1000),  # 必需的时间戳
    'limit': 10  # 最多返回1000条记录，可选
    # 'startTime': 1672502400000, # 可选，查询开始时间（毫秒）
    # 'endTime': 1672588800000,   # 可选，查询结束时间（毫秒）
    # 'fromId': 123456,           # 可选，从指定Trade ID开始查询
}

# 2. 生成签名
query_string = '&'.join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(secret_key.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()
params['signature'] = signature

# 3. 发送请求
url = 'https://fapi.binance.com/fapi/v1/historicalTrades'
headers = {
    'X-MBX-APIKEY': api_key
}

response = requests.get(url, headers=headers, params=params)
trades = response.json()
print(trades)
# # 4. 打印结果
# for trade in trades:
#     print(f"Trade ID: {trade['id']}, "
#           f"Price: {trade['price']}, "
#           f"Qty: {trade['qty']}, "
#           f"Time: {trade['time']}, "
#           f"isBuyer: {trade['isBuyer']}") # isBuyer: True表示你是买方